package com.huawei.config;

import com.huawei.po.TestService;
import com.huawei.po.XxxTypeEnum;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Component
public class MyBean implements ApplicationContextAware {
    
    private ApplicationContext applicationContext;


    private List<TestService> testServiceList;

    @Override
    public void setApplicationContext(ApplicationContext context) {
        this.applicationContext = context;
        // 在这里可以获取到 Spring 容器，进行其他操作
        System.out.println("ApplicationContext 已注入: " + context);
        // 使用 applicationContext 打印所有 Bean 名称
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }

        // 获取TestService所有的实现类
        Map<String, TestService> beansOfType = applicationContext.getBeansOfType(TestService.class);
        this.testServiceList = new ArrayList<>(beansOfType.values());

    }


    /**
     * 获取所有实现类
     *
     * @return
     */
    public List<TestService> getAllList() {
        return testServiceList;
    }

    /**
     * 根据枚举获取某个实现类
     *
     * @param xxxTypeEnum
     * @return
     */
    public TestService get(XxxTypeEnum xxxTypeEnum) {
        Optional<TestService> testService = testServiceList.stream()
                .filter(s -> s.support(xxxTypeEnum))
                .findFirst();

        return testService.orElse(null);
    }

}
